package com.top10.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.top10.bean.JwtUtil;
import com.top10.bean.ResponseBean;
import com.top10.common.Const;
import com.top10.entity.*;
import com.top10.entity.vo.*;
import com.top10.mapper.GoodsMapper;
import com.top10.mapper.OrderMapper;
import com.top10.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.top10.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author su
 * @since 2018-10-05
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ISpecialPriceService iSpecialPriceService;
    @Autowired
    private IGoodsDetailedService iGoodsDetailedService;

  /*  @Autowired
    private IGoodsService iGoodsService;

    @Autowired
    private ISpecialPriceService iSpecialPriceService;

    @Autowired
    private IOrderDetailedService iOrderDetailedService;
    @Autowired
    private IStockService iStockService;

    @Autowired
    private ICouponService iCouponService;


    @Autowired
    private IUserService iUserService;

    @Autowired
    private IUserCartService iUserCartService;



    @Autowired
    private  ICouponUserService iCouponUserService;

    @Autowired
    private  IGoodsDetailedService iGoodsDetailedService;*/


//    @Override
//    public List<OrderVo> selectlistorder(String useruuid, long type) {
//        return orderMapper.selectlistorder(useruuid,type);
//    }


    @Override
    public List<OrderVo> selectlistorder(String useruuid, long type) {
        Gson gson = new GsonBuilder().serializeNulls()
                .setPrettyPrinting()
                .disableHtmlEscaping()
                .create();
        List<OrderVo> orderVoList= orderMapper.selectlistorder(useruuid,type);
        for(OrderVo orderVo:orderVoList){
            Double subtotal=0.0;
            List<OrdetailVo> ordetailVos=orderVo.getOrdetailVos();
            for(OrdetailVo ordetailVo:ordetailVos){


                 GoodsDetailed goodsDetailed=iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("goods_uuid",ordetailVo.getUuid()));
                SpecialPrice specialPrice3=iSpecialPriceService.selectOne(new EntityWrapper<SpecialPrice>()
                        .eq("isdeleted", Const.SpecialIsNotDeleted)
                        .eq("goods_uuid", ordetailVo.getUuid())
                        .gt("end_time",new Date()));
                 if(goodsDetailed!=null && specialPrice3==null){
                   /*  String[] line =ordetailVo.getAttributes().split(",");
                     if(goodsDetailed.getSku()!=null){
                         String sku= goodsDetailed.getSku();
                         List<SkuVo> skuvo=gson.fromJson(sku, new TypeToken<List<SkuVo>>(){}.getType());
                         for (int i=0;i<=skuvo.size()-1;i++){
                             int c=-1;
                             for(int j=0;j<=line.length-1;j++){
                                 if(skuvo.get(i).getKeyin().contains(line[j])){
                                     c++;
                                     if(c==line.length-1){
                                        subtotal=subtotal+ skuvo.get(i).getSkuprice()*ordetailVo.getQuantity();
                                         orderVo.setActualprice(subtotal);
                                     }
                                 }
                             }
                         }
                     }*/
                     subtotal=subtotal+ordetailVo.getPrice()*ordetailVo.getQuantity();
                     orderVo.setActualprice(subtotal);
                 }





                SpecialPrice specialPrice2=iSpecialPriceService.selectOne(new EntityWrapper<SpecialPrice>()
                                .eq("type",1)
                                .eq("isdeleted", Const.SpecialIsNotDeleted)
                                .eq("goods_uuid", ordetailVo.getUuid())
                                .gt("end_time",new Date()));
                if(specialPrice2!=null){
                    ordetailVo.setType(String.valueOf(1));
                    subtotal=subtotal+ordetailVo.getPrice()*ordetailVo.getQuantity();
                    orderVo.setActualprice(subtotal);
                }

                SpecialPrice specialPrice=iSpecialPriceService.selectOne(new EntityWrapper<SpecialPrice>()
                        .eq("type",1)
                        .eq("isdeleted", Const.SpecialIsNotDeleted)
                        .eq("goods_uuid", ordetailVo.getUuid())
                        .gt("end_time",new Date())
                         .ge("limited_number",ordetailVo.getQuantity())
                          .le("min_number",ordetailVo.getQuantity()));
                    if(specialPrice!=null){
                        ordetailVo.setPrice(specialPrice.getSpecialPrice());
                        ordetailVo.setType(String.valueOf(1));
                        if(specialPrice2!=null) {
                            subtotal = subtotal + specialPrice.getSpecialPrice() * ordetailVo.getQuantity() - ordetailVo.getPrice()*ordetailVo.getQuantity();
                        }else{
                            subtotal = subtotal + specialPrice.getSpecialPrice() * ordetailVo.getQuantity();
                        }

                        orderVo.setActualprice(subtotal);
                    }


                 SpecialPrice specialPrice1=iSpecialPriceService.selectOne(new EntityWrapper<SpecialPrice>()
                         .eq("type",2)
                          .eq("isdeleted", Const.SpecialIsNotDeleted)
                             .eq("goods_uuid", ordetailVo.getUuid())
                           .gt("end_time",new Date()));
                    if(specialPrice1!=null){
                        ordetailVo.setPrice(specialPrice1.getSpecialPrice());
                        ordetailVo.setType(String.valueOf(2));
                        subtotal=subtotal+specialPrice1.getSpecialPrice()*ordetailVo.getQuantity();
                        orderVo.setActualprice(subtotal);
                    }
            }

        }

        return orderVoList;
    }

    @Override
    public ShowOrderVo selectOrderDetail(String orderuuid)throws Exception{
        return orderMapper.selectOrderDetail(orderuuid);
    }

  /*  @Transactional
    public Order create(OrderCreateVo orderCreate, HttpServletRequest request) {

        //获取用户的uuid
        //模拟id，以后删除
        String userUuid = JwtUtil.getUuidByToken(request);
        // String userUuid="f0e225b41d4a4715b942f9e1897a1c8b";
        *//* String userUuid="0f24d82671dd4e46b6aa1fa67f13d6fb";*//*
        User user = iUserService.selectOne(new EntityWrapper<User>().eq("uuid", userUuid));


        //订单商品总数量
        int aggregateAmount=0;

        //订单总金额
        double aggregatePrice =0 ;

        //订单小计支付金额（包括邮费、减去优惠券、积分）
        double actual_price=0;

        DecimalFormat decimalFormat = new DecimalFormat("#.00");

        Order order=new Order();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

        String orderid=simpleDateFormat.format(new Date())+RandomUtils.makeRandomDigit6();
        String orderuuid=RandomUtils.makeUUID();
        order.setShopUuid(orderCreate.getShopUuid());
        order.setUuid(orderuuid);
        order.setOrderid(orderid);


        for(OrderCreateDetailedVo orderDetailed:orderCreate.getOrderDetailCreateVo())
        {
            OrderDetailed orderDetail =new OrderDetailed();
            SpecialPrice speciaGood=iSpecialPriceService.selectOne(new EntityWrapper<SpecialPrice>().eq("isdeleted", Const.SpecialIsNotDeleted)
                    .eq("goods_uuid",orderDetailed.getGoodsUuid()));
            //判断是否为特价商品
            if(speciaGood!=null){


                GoodsDetailed goodsDetailed=iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("goods_uuid",orderDetailed.getGoodsUuid()));
                if(goodsDetailed!=null){
                    orderDetail.setGoodsDetailedUuid(goodsDetailed.getUuid());
                }

                orderDetail.setUuid(RandomUtils.makeUUID());
                orderDetail.setOrderUuid(orderuuid);
                orderDetail.setGoodsName(orderDetailed.getGoodsName());

                orderDetail.setGoodsDetailedUuid(goodsDetailed.getUuid());
                orderDetail.setAttributes(orderDetailed.getAttributes());
                orderDetail.setPrice(speciaGood.getSpecialPrice());
                Integer Quantity=orderDetailed.getQuantity();
                orderDetail.setQuantity(Quantity);
                //该商品总价
                double subtotal = Double.parseDouble(decimalFormat.format(speciaGood.getSpecialPrice() * orderDetailed.getQuantity()));
                orderDetail.setSubtotal(subtotal);

                //实际需要支付的总价
                orderDetail.setActualSubtotal(subtotal);
                orderDetail.setCreatetime(new Date());

                //判断库存数量是否足够
                GoodsDetailed stock=iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("isdeleted",Const.IsNotDelete)
                        .eq("goods_uuid",orderDetailed.getGoodsUuid()));
                if(stock==null){
                    throw  new RuntimeException("库存中不存在该商品");
                }
                if(stock.getStock()<orderDetailed.getQuantity() || stock.getStock()<1){

                    throw  new RuntimeException("库存不足");
                }
                //商品总价
                aggregatePrice+=subtotal;

                //商品总价
                actual_price+=subtotal;

                //商品总数
                aggregateAmount+=Quantity;

                iOrderDetailedService.insert(orderDetail);


                //减掉库存
                Integer actualstock =stock.getStock()-orderDetailed.getQuantity();
                stock.setStock(actualstock);
                stock.setUpdatetime(new Date());
                iGoodsDetailedService.updateById(stock);
                //清除掉购物车中该商品


                UserCart userCart=iUserCartService.selectOne(new EntityWrapper<UserCart>().eq("user_uuid",user.getUuid())
                        .eq("goods_uuid",orderDetailed.getGoodsUuid()));
                if(userCart!=null){
                    userCart.setIsdeleted(true);
                    iUserCartService.updateById(userCart);
                }
            }


            else {

                Goods goods =iGoodsService.selectOne(new EntityWrapper<Goods>().eq("uuid",orderDetailed.getGoodsUuid())
                        .eq("isdeleted",Const.IsNotDelete));
                GoodsDetailed goodsDetailed=iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("goods_uuid",orderDetailed.getGoodsUuid()));
                if(goods==null || goodsDetailed==null){
                    throw new RuntimeException("该商品已下架");
                }
                orderDetail.setGoodsDetailedUuid(goodsDetailed.getUuid());
                orderDetail.setUuid(RandomUtils.makeUUID());
                orderDetail.setOrderUuid(orderuuid);
                orderDetail.setGoodsName(goods.getName());


                orderDetail.setAttributes(orderDetailed.getAttributes());
                orderDetail.setPrice(goodsDetailed.getPrice());
                Integer Quantity=orderDetailed.getQuantity();
                orderDetail.setQuantity(Quantity);

                //该商品价格
                double subtotal = Double.parseDouble(decimalFormat.format(goodsDetailed.getPrice() * orderDetailed.getQuantity()));

                orderDetail.setSubtotal(subtotal);
                orderDetail.setCreator(user.getUuid());
                orderDetail.setActualSubtotal(subtotal);
                orderDetail.setCreatetime(new Date());
                orderDetail.setRemark(orderDetailed.getRemark());


                //  判断库存数量是否足够
                GoodsDetailed stock=iGoodsDetailedService.selectOne(new EntityWrapper<GoodsDetailed>().eq("isdeleted",Const.IsNotDelete)
                        .eq("goods_uuid",orderDetailed.getGoodsUuid()));
                if(stock==null){
                    throw new RuntimeException("库存中不存在该商品");
                }
                if(stock.getStock()<orderDetailed.getQuantity() || stock.getStock()<1){

                    throw  new RuntimeException("库存不足");
                }

                //商品总价
                aggregatePrice+=subtotal;

                //商品总价
                actual_price+=subtotal;

                //商品总数
                aggregateAmount+=Quantity;

                iOrderDetailedService.insert(orderDetail);

                // 减掉库存
                Integer actualstock =stock.getStock()-orderDetailed.getQuantity();

                stock.setStock(actualstock);
                stock.setUpdatetime(new Date());

                iGoodsDetailedService.updateById(stock);



                UserCart userCart=iUserCartService.selectOne(new EntityWrapper<UserCart>().eq("user_uuid",user.getUuid())
                        .eq("goods_uuid",orderDetailed.getGoodsUuid()));
                if(userCart!=null){
                    userCart.setIsdeleted(true);
                    iUserCartService.updateById(userCart);
                }
            }


        }


        if(orderCreate.getCardCouponsUuid()!=null) {
            //todo
            //更新

            //减去该商品优惠券价格
            Coupon coupon = iCouponService.selectOne(new EntityWrapper<Coupon>().eq("uuid", orderCreate.getCardCouponsUuid()).ge("", new Date()));

            if (coupon == null) {
                throw new RuntimeException("该购物券已过期");
            }

            if (coupon.getRequirementAmount().doubleValue() > aggregatePrice) {
                throw new RuntimeException("不满足优惠券的使用条件");
            }


            Double couponprice = coupon.getAmount().doubleValue();


            //该优惠券的总数量减一
            // coupon.setCouponNum(coupon.getCouponNum() - 1);

            //减去优惠券的价格
            actual_price = aggregatePrice - couponprice;

            //  设置用户优惠券已使用
            CouponUser couponUser = iCouponUserService.selectById(user.getUuid());
            couponUser.setIsUsed(String.valueOf(1));

            iCouponUserService.updateById(couponUser);
        }
        //积分
        BigDecimal integral= new BigDecimal(orderCreate.getIntegral()/10).setScale(2, RoundingMode.UP);

        //  减去积分
        actual_price=actual_price-integral.doubleValue();

        //减去用户总积分
        user.setPoint(BigDecimal.valueOf(user.getPoint().doubleValue()-orderCreate.getIntegral().doubleValue()));

        //更新用户积分
        iUserService.updateById(user);

        if(actual_price<0){
            actual_price=0;
        }

        order.setUserUuid(user.getUuid());
        order.setConsigneeUuid(orderCreate.getConsigneeUuid());
        order.setExpressPrice(orderCreate.getExpressPrice());
        //商品总价，还没减去优惠券价格、积分
        order.setAggregateAmount(aggregatePrice);
        //用户实际需要支付的价格
        order.setActualPrice(actual_price);

        //该订单的商品总数
        order.setsQuantity(aggregateAmount);
        order.setIntegral(orderCreate.getIntegral());
        order.setCardCouponsUuid(orderCreate.getCardCouponsUuid());
        //order.setDeliveryUuid(orderCreate.getDeliveryUuid());
        order.setStatus(0);
        //order.setOrderType(1);
        //order.setProvince(orderCreate.getProvince());
        order.setCreatetime(new Date());
        order.setIsdeleted(false);
        order.setPaySellerStatus(false);
        //代支付
        order.setPaytype(3);
        order.setCreator(user.getUuid());
        return order;
    }
*/
    @Override
    public List<OrderPayVo> selectpaylist(String orderuuid) {
        return orderMapper.selectpaylist(orderuuid);
    }
}